/**
 * Created with CLion.
 * Description: 
 * User: loong
 * Date: 2020-01-03
 * Time: 10:58
 */

#include "ShowCode.h"
#include "Ui_ShowCode.h"

using namespace qrcodegen;

ShowCode::ShowCode(QWidget *parent,QString string)
        : QDialog(parent), ui(new Ui::ShowCode) {
    ui->setupUi(this);
    setWindowTitle("二维码");

    QString pic = "/home/loong/workdir/plantRobot/pic/";
    pic.append(string);
    qDebug()<<pic;

    QPixmap *pixmap = new QPixmap(pic);
    pixmap->scaled(ui->label->size(), Qt::KeepAspectRatio);
    ui->label->setScaledContents(true);
    ui->label->setPixmap(*pixmap);
    ui->label->show();
}

ShowCode::~ShowCode() {
    delete ui;
}


QString ShowCode::GenerateQrCode(QString string) {
    //char string[100]= {0};
    //char *stringID = (char *)id;
    //strcat(string,"http://101.200.148.140:8080/TeamProject/Qrquery?action=qrquery&qrqueryid=");
    //strcat(string,stringID);

    //printf("strng:%s",string);
    // Manual operation


    //QPixmap map(400,400);
    //QPainter painter(&map);
    //ShowCode::paintQR(painter,QSize(400,400),string, QColor("white"),QColor("black"));
    QString pic = "/home/loong/workdir/plantRobot/pic/";
    pic.append(string);
    pic.append(".png");
    qDebug()<<pic;
    //QPixmap pix;
    //QImage image("/home/loong/workdir/plantRobot/pic/qq.jpg");//filename，图片的路径名字
    //ui->label->setPixmap(pix.fromImage(image));
    //ui->label->setScaledContents(true);
    //ui->label->show();

    QPixmap *pixmap = new QPixmap(pic);
    pixmap->scaled(ui->label->size(), Qt::KeepAspectRatio);
    ui->label->setScaledContents(true);
    ui->label->setPixmap(*pixmap);
    ui->label->show();
}

void ShowCode::paintQR(QPainter &painter, const QSize sz, const QString &data, QColor fg, QColor bg){
    char *str=data.toUtf8().data();
    // NOTE: At this point you will use the API to get the encoding and format you want, instead of my hardcoded stuff:
    QrCode qr = QrCode::encodeText(str, QrCode::Ecc::ECCHIGH);
    const int s=qr.size>0?qr.size:1;
    const double w=sz.width();
    const double h=sz.height();
    const double aspect=w/h;
    const double size=((aspect>1.0)?h:w);
    const double scale=size/(s+2);

    painter.setPen(Qt::NoPen);
    // Setting the background color....
    painter.setBrush(bg);
    for(int y=0; y<400; y++) {
        for(int x=0; x<400; x++) {
            const double rx1=(x+1)*scale, ry1=(y+1)*scale;
            QRectF r(x, y, 1, 1);
            painter.drawRects(&r,1);
        }
    }
    //Drawing the Code....
    painter.setBrush(fg);
    for(int y=0; y<s; y++) {
        for(int x=0; x<s; x++) {
            const int color = qr.getModule(x, y);  // 0 for white, 1 for black
            if(0x0!=color) {
                const double rx1=(x+1)*scale, ry1=(y+1)*scale;
                QRectF r(rx1, ry1, scale, scale);
                painter.drawRects(&r,1);
            }
        }
    }
}